package cn.com.openportal.ffw.modules.sys.controller;

import cn.com.openportal.ffw.common.annotation.SysLog;
import cn.com.openportal.ffw.common.exception.RRException;
import cn.com.openportal.ffw.common.utils.Constant;
import cn.com.openportal.ffw.common.utils.PageUtils;
import cn.com.openportal.ffw.common.utils.R;
import cn.com.openportal.ffw.common.validator.ValidatorUtils;
import cn.com.openportal.ffw.modules.sys.entity.SysRoleEntity;
import cn.com.openportal.ffw.modules.sys.entity.SysUserEntity;
import cn.com.openportal.ffw.modules.sys.service.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 角色管理
 *
 * @author LeeSon
 */
@RestController
@RequestMapping("/sys/role")
public class SysRoleController extends AbstractController {
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private SysDeptService sysDeptService;

    /**
     * 角色列表
     */
    @GetMapping("/list")
    @RequiresPermissions("sys:role:list")
    public R list(@RequestParam Map<String, Object> params) {
        //如果不是超级管理员，则只查询自己创建的角色列表
        if (getUserId() != Constant.SUPER_ADMIN) {
            //params.put("createUserId", getUserId());
            params.put("roleIds", getRoleIdList());
        }

        PageUtils page = sysRoleService.queryPage(params);

        return R.ok().put("page", page);
    }

    /**
     * 角色列表
     */
    @GetMapping("/select")
    @RequiresPermissions("sys:role:select")
    public R select() {
        Map<String, Object> map = new HashMap<>();
        //如果不是超级管理员，则只查询自己所拥有的角色列表
//        if (getUserId() != Constant.SUPER_ADMIN) {
//            map.put("create_user_id", getUserId());
//        }
//        List<SysRoleEntity> list = (List<SysRoleEntity>) sysRoleService.listByMap(map);
        if (getUserId() != Constant.SUPER_ADMIN) {
            List<Long> roleIds=getRoleIdList();
            if(roleIds.size()==0){
                roleIds.add(0L);
            }
            List<SysRoleEntity> list = sysRoleService.getBaseMapper().selectList(new QueryWrapper<SysRoleEntity>()
                    .in(null != roleIds && roleIds.size() > 0, "role_id", roleIds));
            return R.ok().put("list", list);
        }

        List<SysRoleEntity> list = (List<SysRoleEntity>) sysRoleService.listByMap(map);

        return R.ok().put("list", list);
    }

    /**
     * 角色信息
     */
    @GetMapping("/info/{roleId}")
    @RequiresPermissions("sys:role:info")
    public R info(@PathVariable("roleId") Long roleId) {

        checkPrems(roleId);

        SysRoleEntity role = sysRoleService.getById(roleId);

        //查询角色对应的菜单
        List<Long> menuIdList=sysRoleMenuService.queryMenuIdList(roleId);
        role.setMenuIdList(menuIdList);

        return R.ok().put("role", role);
    }

    /**
     * 保存角色
     */
    @SysLog("保存角色")
    @PostMapping("/save")
    @RequiresPermissions("sys:role:save")
    public R save(@RequestBody SysRoleEntity role) {

        checkPrems(role.getRoleId());

        ValidatorUtils.validateEntity(role);

        role.setCreateUserId(getUserId());

        sysRoleService.saveRole(role);

        return R.ok();
    }

    /**
     * 修改角色
     */
    @SysLog("修改角色")
    @PostMapping("/update")
    @RequiresPermissions("sys:role:update")
    public R update(@RequestBody SysRoleEntity role) {

        checkPrems(role.getRoleId());

        ValidatorUtils.validateEntity(role);

        role.setCreateUserId(sysRoleService.getById(role.getRoleId()).getCreateUserId());

        sysRoleService.update(role);

        return R.ok();
    }

    /**
     * 删除角色
     */
    @SysLog("删除角色")
    @PostMapping("/delete")
    @RequiresPermissions("sys:role:delete")
    public R delete(@RequestBody Long[] roleIds) {

        for (Long roleId : roleIds) {
            checkPrems(roleId);
        }

        sysRoleService.deleteBatch(roleIds);

        return R.ok();
    }

    /**
     * 检查权限
     */
    private void checkPrems(Long roleId) {
        if (getUserId() != Constant.SUPER_ADMIN) {
            //如果不是超级管理员，则需要判断角色是否自己创建
//            if (sysRoleService.getById(roleId).getCreateUserId().longValue() != getUserId().longValue()) {
//                throw new RRException("权限限制");
//            }
            List<Long> deptIds=sysDeptService.getSubDeptIdList(getUser().getDeptId());
            deptIds.add(getUser().getDeptId());
            SysRoleEntity role=sysRoleService.getById(roleId);
            if(null!=role){
                Long deptIdF=role.getDeptId();
                if(null!=deptIdF){
                    if(!deptIds.contains(deptIdF)){
                        throw new RRException("权限限制");
                    }
                }
            }
        }
    }

    private List<Long> getRoleIdList(){
        List<Long> roleIdList = new ArrayList<>();
        SysUserEntity sysUserEntity = getUser();
        List<Long> deptIds = sysDeptService.getSubDeptIdList(sysUserEntity.getDeptId());
        deptIds.add(sysUserEntity.getDeptId());
        List<SysRoleEntity> roleList = sysRoleService.getBaseMapper().selectList(new QueryWrapper<SysRoleEntity>()
                .select("role_id")
                .in(null != deptIds && deptIds.size() > 0, "dept_id", deptIds));
        for (SysRoleEntity e : roleList) {
            roleIdList.add(e.getRoleId());
        }
        return  roleIdList;
    }
}
